<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="物料分类" prop="materialTyp">
        <el-select v-model="queryParams.materialType" placeholder="请选择物料类型" clearable style="width: 200px">
          <el-option v-for="dict in material_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['gc:zhz:xz']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="groupList">
      <el-table-column label="类型" prop="materialTypeName" width="120" />
      <el-table-column label="名称" prop="materialName" :show-overflow-tooltip="true" width="200"></el-table-column>
      <el-table-column label="图片" prop="materialImageUrl" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.materialImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="materialInventoryNum" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="供应商" prop="supplierName" :show-overflow-tooltip="true" width="120"></el-table-column>
      <el-table-column label="采购单价" prop="materialPurchaseUnitPrice" align="center" width="100"></el-table-column>
      <el-table-column label="采购链接" align="center" width="200" prop="materialPurchaseLink"> </el-table-column>
      <el-table-column label="采购单位" align="center" width="120" prop="materialPurchaseUnit"> </el-table-column>
      <el-table-column label="备注" align="center" width="200" :show-overflow-tooltip="true" prop="remark"> </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改物料配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择供应商" clearable style="width: 200px">
            <el-option v-for="dict in supplierListData" :key="dict.id" :label="dict.supplierName" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-select v-model="form.materialType" placeholder="请选择物料类型" clearable style="width: 200px">
            <el-option v-for="dict in material_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料图片" prop="materialImageUrl">
          <el-upload ref="uploadRef" style="width: 100%;" list-type="picture-card" v-model:file-list="fileList" :headers="headers" class="upload-demo"
            :action="actionUrl" :limit="1" :data="{ type: 0,  tenantGroupId: tenantGroupId  }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess"
            :on-success="handleUploadSuccess" :on-exceed="handleExceed">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="库存数量" prop="materialInventoryNum">
          <el-input-number style="width:200px" v-model="form.materialInventoryNum" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="库存单位" prop="materialInventoryUnit">
          <el-select v-model="form.materialInventoryUnit" placeholder="请选择库存单位" clearable style="width: 200px">
            <el-option v-for="dict in material_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购单价" prop="materialPurchaseUnitPrice">

          <el-input-number style="width:200px" v-model="form.materialPurchaseUnitPrice" placeholder="请输入采购单价" />
        </el-form-item>
        <el-form-item label="采购单位" prop="materialPurchaseUnit">
          <el-select v-model="form.materialPurchaseUnit" placeholder="请选择采购单位" clearable style="width: 200px">
            <el-option v-for="dict in material_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购链接" prop="materialPurchaseLink">
          <el-input v-model="form.materialPurchaseLink" placeholder="请输入采购链接" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="style">
  import { listType } from "@/api/order/type";
  import {
    list,
    add,
    edit,
    remove,
    supplierList
  } from "@/api/order/material"
  import {
    listapplicant,
  } from "@/api/system/applicant";
  import baseForm from "../hooks/useOrderBase";
  const { headers, actionUrl, fileList, fileList2, fileList3, tenantGroupId } = baseForm();
  const router = useRouter();
  const route = useRoute()
  const { proxy } = getCurrentInstance();
  const { material_type, material_unit } = proxy.useDict("material_type", "material_unit");
  const TypeList = ref([])
  const groupList = ref([]);
  const open = ref(false);
  const appLicationList = ref([])
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const deptExpand = ref(true);
  const deptNodeAll = ref(false);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const supplierListData = ref([])

  function getsupplierList() {
    supplierList({}).then((res) => {
      supplierListData.value = res.rows
    })
  }
  // 文件上传覆盖
  const uploadRef = ref();

  function handleExceed(files) {
    uploadRef.value.clearFiles();
    nextTick(() => {
      uploadRef.value.handleStart(files[0]);
      uploadRef.value.submit();
    });
  }
  // 上传成功回调
  function handleUploadSuccess(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList.value = fileList.value.map((r) => { return r.response.data });
      form.value.materialImageUrl = res.data.url;
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      materialTyp: null,
      fashionNo: undefined,
      materialName: undefined
    },
    rules: {
      supplierId: [{ required: true, message: "请选择供应商", trigger: "blur" }],
      materialType: [{ required: true, message: "请选择物料类型", trigger: "blur" }],
      materialName: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
      artDesignerWages: [{ required: true, message: "美工工价不能为空", trigger: "blur" }],
      fashionFabric: [{ required: true, message: "物料不能为空", trigger: "blur" }],
    },
  });
  const { queryParams, form, rules } = toRefs(data);

  /** 查询物料列表 */
  function getList() {
    loading.value = true;
    let formQueryParam = { ...queryParams.value };
    formQueryParam.expireTemp = formQueryParam.expireTemp == 0 ? '' : formQueryParam.expireTemp
    list(proxy.addDateRange(formQueryParam, dateRange.value)).then(response => {
      groupList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      expireTemp: '',
      styleName: undefined,
      styleLinkName: undefined,
      styleLinkMobile: '',
      styleExpireStatus: '',
      styleAvl: ''
    }
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除物料编号为"' + ids + '"的数据项?').then(function() {
      return remove(ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }

  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }


  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
      styleName: undefined,
      styleLinkName: undefined,
      styleLinkMobile: '',
      styleExpireStatus: 'F',
      styleAvl: 'Y',
      tenantCreateParams: []
    };
    proxy.resetForm("roleRef");
  }

  /** 添加物料 */
  function handleAdd() {
    reset();
    fileList.value = []
    open.value = true;
    getsupplierList()
    title.value = "添加物料";
  }

  /** 修改物料 */
  function handleUpdate(row) {
    title.value = "修改物料";
    getsupplierList();

    form.value = { ...row }
    fileList.value = form.value.materialImageUrl ? form.value.materialImageUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : [];
    open.value = true;
  }

  /** 提交按钮 */
  function submitForm() {
    let pass = true
    if (!form.value.id && form.value.tenantCreateParams && form.value.tenantCreateParams.length) {
      form.value.tenantCreateParams.forEach((a, index) => {
        if (!a.applicantId || !a.tenantCode || !a.tenantName) {
          pass = false
        }
      })
    }
    if (!pass) {
      proxy.$modal.msgWarning("物料列表下内容不能有空~");
      return
    }
    // if (form.value.styleExpireStatus == 'T' && !form.value.styleExpireDate) {
    //   proxy.$modal.msgWarning("请选择截止日期~");
    //   return
    // }
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.id != undefined) {
          edit(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          add(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  getList();
</script>